<?php
/**
 * 查询数据
 */
require_once '../common.php';

try {
    // 数据库名.表名
    $table_name = 'phporm.app_info';

    // 实例化
    $model = PHPOrm::init($table_name);

    // 查询一条数据 getOne 第一个参数（必）：where语句  第二个参数（非必）：字段
    $where = [
        'name' => '第40个应用'
    ];
    $one_app = $model->getOne($where);
    var_dump($one_app);

    $one_app = $model->getOne($where, ['id', 'description']);
    var_dump($one_app);

    // 查询所有 getAll 第一个参数（非必）：字段
    $all_apps = $model->getAll(['id', 'description']);
    var_dump($all_apps);

    // 查询多个 get  第一个参数（必）：where语句  第二个参数（非必）：字段
    $where = [
        'product_id' => 3
    ];
    $apps = $model->get($where, ['id', 'description']);
    var_dump($apps);

    // 排序，order_by必须在get前面
    $where = [
        'product_id' => 3,
        'service_id' => 2
    ];
    $apps = $model->order_by(['id' => 'desc'])->get($where, ['id']);
    var_dump($apps);

    // limit，必须在get前面
    $where = [
        'product_id' => 3,
        'service_id' => 2
    ];
    $apps = $model->order_by(['id' => 'desc'])->limit(2)->get($where, ['id']);
    var_dump($apps);

    // 大于/小于查询 相当于：select id from app_info where product_id = 3 and created_at > 昨天0点 and created_at < 现在 and status <= 4
    // gt  大于查询 >
    // lg  小于查询 <
    // egt 大于等于查询 >=
    // elt 小于等于查询 <=
    $where = [
        'product_id' => 3,
        'status' => ['elt' => 4]
    ];
    $start_time = date('Y-m-d H:i:s', strtotime('-1 day'));
    $end_time = date('Y-m-d H:i:s');
    $where['created_at']['gt'] = $start_time;
    $where['created_at']['lt'] = $end_time;

    $apps = $model->get($where, ['id']);
    var_dump($apps);

    // 不等于查询 相当于：select id from app_info where product_id != 1 and product_id != 2 and status != 3
    // ne 不等于 支持数组也支持字符串
    $where = [
        'product_id' => ['ne' => [1, 2]],
        'status' => ['ne' => 3]
    ];

    $apps = $model->get($where, ['id']);
    var_dump($apps);

    // like查询 相当于：select id,name from app_info where name like '%申请%'
    $where = [
        'name' => ['like' => '%申请%']
    ];
    $apps = $model->get($where, ['id', 'name']);
    var_dump($apps);

    // is NULL/is not NULL 查询 相当于：select id,name from app_info where deleted_at is NULL
    // is_null   is NULL
    // is_not_null   is NOT NULL
    $where = [
        'deleted_at' => ['is_null' => '']
    ];
    $apps = $model->get($where, ['id', 'name']);
    var_dump($apps);

    // in/not in 查询 相当于：select id,app_type,product_id from app_info where app_type in ('appsvr', 'svr') and product_id not in (1, 3)
    $where = [
        'app_type' => ['in' => ['appsvr', 'svr']],
        'product_id' => ['not_in' => [1, 3]]
    ];
    $apps = $model->get($where, ['id', 'name', 'app_type', 'product_id']);
    var_dump($apps);

    // 查询上次SQL
    var_dump($model->last_sql);

    // 查询具体的报错
    var_dump($model->error);
} catch (\DB_Exception $e) {
    var_dump('数据库错误');
    var_dump($e->getMessage());
} catch (\Exception $e) {
    var_dump('其他错误');
    var_dump($e->getMessage());
}